package org.example.demowebsrocket.handler;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.demowebsrocket.model.Message;
import org.example.demowebsrocket.service.WebSocketSessionManager;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.List;

/**
 * @author zhaokaifan
 */
@Slf4j
@Component
@AllArgsConstructor
public class WebSocketHandler extends TextWebSocketHandler {
    private final ObjectMapper objectMapper;
    private final WebSocketSessionManager sessionManager;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String username = getUsernameFromSession(session);
        if (StrUtil.isNotEmpty(username)) {
            sessionManager.addSession(username, session);
            log.info("用户{}已连接", username);
            //发送连接成功的系统消息
            Message message = new Message(
                    "SYSTEM", "系统", null, "您已成功连接到WebSrockt服务器"
            );
            sendMessageToUser(username, message);
        } else {
            log.error("无法获取用户名,关闭连接");
            session.close(CloseStatus.POLICY_VIOLATION.withReason("用户名不能为空"));
        }

    }

    public void sendMessageToUser(String username, Message message) {
        WebSocketSession session = sessionManager.getSession(username);
        if (session != null && session.isOpen()) {
            sendMessageToSession(session, message);
        }
    }

    private void sendMessageToSession(WebSocketSession session, Message message) {
        try {
            String jsonMessage = objectMapper.writeValueAsString(message);
            session.sendMessage(new TextMessage(jsonMessage));
        } catch (IOException e) {
            log.error("发送消息失败", e);
        }
    }

    private static String getUsernameFromSession(WebSocketSession session) {
        return (String) session.getAttributes().get("username");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
    }
}
